<template>
  <div>
    <div class="ccui-navigation">
      <!-- 面包屑 -->
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval'
          }"
          >结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval'
          }"
          >运输结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          v-if="$route.query.taizhangDetails == 1"
          :to="{
            path: '/settlement-management/transportation-settlement-standing-book/item-list'
          }"
          >结算单台账</el-breadcrumb-item
        >
        <el-breadcrumb-item
          v-else-if="isApproval"
          :to="{
            path: '/settlement-management/transportation-settlement-approval/settlement-list-pending'
          }"
          >结算单审批</el-breadcrumb-item
        >
        <el-breadcrumb-item
          v-else
          :to="{
            path: breadUrl
          }"
          >结算单维护</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb"
            >查看 {{ settlementForm.settlementName }}</span
          >
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <!--左边详情部分-->
      <div
        :class="[
          approvingStatus ? 'detail-box' : 'details-box',
          'ccui-clearfix'
        ]"
      >
        <div class="detail-info">
          <!--审批状态 icon-->
          <div class="detail-info-el-Label">
            <el-label :type="approving" v-if="approvingStatus"></el-label>
          </div>
          <div class="detail-info-form-container self-container">
            <el-tabs
              v-model="activeName"
              @tab-click="handleClick"
              class="el-tabs__customize"
            >
              <el-tab-pane label="基本信息" name="first">
                <baseInfoCheck
                  ref="bassettlement-checkeInfo"
                  :detail="detailInfo"
                  :myId="myId"
                  :settlement-form="settlementForm"
                />
              </el-tab-pane>

              <el-tab-pane label="结算单明细" name="second">
                <keep-alive>
                  <financeInfoCheck
                    ref="financeInfo"
                    :settlementList="settlementList"
                    :detail="detailInfo"
                  />
                </keep-alive>
              </el-tab-pane>

              <el-tab-pane label="附件" name="fouth">
                <keep-alive>
                  <upload-table
                    v-if="isRange"
                    ref="contractAppendix"
                    state="detail"
                    v-model="fileList"
                  />
                </keep-alive>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!--右边审批状态-->
        <approval-read-record
          v-if="isTrue"
          :approvalRecordData="activities"
        ></approval-read-record>
      </div>
    </div>
    <!--  底部导航栏及签名导出  -->
    <bottomGuide
      v-if="['5', '22'].includes(settlementForm.settlementStatus) && isTrue"
      exportMethod="get"
      busiType="105"
      methodGetPageType="exportSettleTrans"
      approvalStatus="approvaled"
      :curPageId="$route.params.id"
      :businessCode="businessCode"
      @handleBack="handleBack"
    />
    <!--  按钮  -->
    <el-bottom-guide v-else>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            v-if="
              !isApproval &&
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="openReturnDialog"
            >退回供应商
          </el-button>
        </li>
        <li>
          <el-button
            v-if="
              !isApproval &&
              settlementForm.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(settlementForm.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="submitSettlement"
            >保存并提交
          </el-button>
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>

    <returnDialog ref="returnDialog" @getValue="getValue" />
  </div>
</template>

<script>
import jsList from "../js";
import baseInfoCheck from "../components/baseInfoCheck";
import financeInfoCheck from "../components/financeInfoCheck";
import {
  getSettlementById,
  sendBackSupplierSettlement,
  editTransSettlement,
  getUserInfo
} from "../api/transportation-approval";
import { addUrlPerFix } from "@/basa/utils";
import UploadTable from "@/basa/components/public/uploadInfo3";
import approvalReadRecord from "@/basa/components/public/approvalRecord";
import returnDialog from "@/app/transportation-settlement/transportation-maintenance-approval/components/returnDialog";
import publicComponent from "@/basa/components/public";

export default {
  // mixins: [Mixin],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    UploadTable,
    baseInfoCheck,
    financeInfoCheck,
    approvalReadRecord,
    returnDialog,
    bottomGuide: publicComponent.bottomGuide
  },
  data() {
    return {
      businessCode: "",
      downloadUrl: this.$addUrlPerFix(process.env.VUE_APP_BASE_URL),
      activities: [],
      settlementForm: {
        pcConcId: "", // 基础合同id
        scConcId: "", // 结算申请单id
        materialName: "", // 合同名称
        materialCode: "", // 合同编号
        partyAName: "", // 合同甲方
        partyBId: "", // 合同乙方id
        partyBName: "", // 合同乙方
        materialName1: "", //供应商
        taxRatePercent: "", // 税率
        nowTotalContractPriceIncludeTax: "", // 合同金额（含税）
        settleTotalAmtIncludeTax: "", // 开累结算金额（含税）
        payedTotalAmtIncludeTax: "", // 开累支付金额
        settleTotalUnpaidAmt: "", // 开累结算未支付金额
        contractBalance: "", // 合同余额（含税）
        settlementNum: "", // 结算单编号
        settlementPeriod: "", // 结算期次
        currentSettlePayAmtIncludeTax: "", // 本期支付金额
        currentSettleAmtIncludeTax: "", // 本期结算金额（含税）
        currentSettleUnpayAmtIncludeTax: "", // 本期结算未支付金额（含税）
        paymentNum: "", // 支付单编号
        compiler: "", // 编制人
        compilerId: "", // 编制人id
        paymentApplyDate: "", // 支付申请日期
        remark: "" // 备注
      },
      fileList: [],
      jsList,
      breadcrumbLastItem: "物资合同",
      activeName: "first",
      isTrue: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      myId: "",
      tabBtn: [
        { label: "基本信息", value: "baseInfo" },
        { label: "财务信息", value: "financeInfo" },
        { label: "采购清单", value: "purchaseList" }
      ],
      summaryArr: ["subContractorsName"],
      tableTheadOptions: [
        {
          label: "合同编号",
          prop: "subContractName",
          width1: 120
        },
        {
          label: "合同名称",
          prop: "subContractorsName"
        }
      ],
      oneLineTableData: [
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 }
      ],
      arr1: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" },
        { id: 3, name: "cc" }
      ],
      arr2: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" }
      ],
      a: [],
      settlementList: [],
      breadUrl: "",
      isRange: false,
      approving: "", // 审批状态
      approvingStatus: true, // 审批状态展示
      approvingType: {
        1: "approving", // 审批中
        2: "withdrawn", // 已撤回
        3: "approvaled", // 审批通过
        4: "sendback", // 审批退回
        5: "unapproval" // 审批不通过
      }
    };
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  computed: {
    isApproval() {
      return this.$route.query.type == "approval";
    }
  },
  created() {
    if (this.isTz == 1) {
      this.breadItem = "结算单台账";
      this.breadUrl = "/settlement-management/transportation-standing-book";
    } else {
      this.breadItem = "结算单维护";
      this.breadUrl =
        "/settlement-management/transportation-maintenance-approval";
    }
    let a = [...this.arr1];
    for (let i = 0; i < this.arr1.length; i++) {
      let flag = false;
      for (let j = 0; j < this.arr2.length; j++) {
        if (this.arr1[i].id === this.arr2[j].id) flag = true;
      }
      if (flag)
        a.splice(
          a.findIndex(_ => _.id === this.arr1[i].id),
          1
        );
    }
    console.log(a);
    this.myId = this.$route.params.id;
    this.init();
    this.getUserInfo();
  },
  activated() {
    this.init();
    this.activeName = "first";
  },
  deactivated() {
    // this.nextIsTrue();
    this.isTrue = false;
    this.isRange = false;
  },
  methods: {
    // 处理附件入参
    handleFilesParams() {
      let gistUploadIds = [],
        otherUploadIds = [];

      this.fileList.map((e, i) => {
        if (e.fileType == 51) {
          gistUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        } else {
          otherUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        }
      });
      return {
        gistUploadIds: gistUploadIds,
        otherUploadIds: otherUploadIds
      };
    },

    // sort 排序
    handleSort(property) {
      return function (a, b) {
        return a[property] - b[property];
      };
    },
    // 退回操作
    openReturnDialog() {
      this.$refs["returnDialog"].visibleDialog = true;
    },
    // 退回弹框确定调用接口
    getValue(val) {
      let params = {
        id: +this.$route.params.id,
        supplierSendBackReason: val,
        isShowPageLoading: true
      };
      sendBackSupplierSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: "保存并提交成功"
        });
        this.handleBack();
      });
    },
    init() {
      // const { id } = this.$route.params;
      const data = {
        id: this.myId,
        isShowPageLoading: true
      };
      getSettlementById(data)
        .then(res => {
          this.businessCode = res.data.data.settlementBO.settlementCode;
          this.settlementForm = res.data.data.settlementBO;
          this.settlementForm.contractMoney = this.settlementForm.contractMoney
            ? this.settlementForm.contractMoney.toFixed(2)
            : "";
          this.settlementList = res.data.data.settlementBOList;
          this.settlementList.forEach(row => {
            row.unTransportCount = row.unTransportCount.toFixed(3);
            row.settlementCount = row.settlementCount
              ? row.settlementCount.toFixed(3)
              : "";
            row.unitPriceWithTax = row.unitPriceWithTax
              ? row.unitPriceWithTax.toFixed(2)
              : "";
            row.unitPriceWithoutTax = row.unitPriceWithoutTax
              ? row.unitPriceWithoutTax.toFixed(2)
              : "";
            row.moneyWithoutTax = row.moneyWithoutTax
              ? row.moneyWithoutTax.toFixed(2)
              : "";
          });
          res.data.data.gistFiles.map(e => {
            e.fileType = 51;
            e.fileTypeName = "结算依据";
          });
          res.data.data.otherFiles.map(e => {
            e.fileType = 52;
            e.fileTypeName = "其他";
          });
          this.fileList = [
            ...res.data.data.gistFiles,
            ...res.data.data.otherFiles
          ];
          this.fileList.sort(this.handleSort("sn"));
          this.isRange = true;
          this.showArrpoval = true;
          this.activities = res.data.data.approveRecords;
          this.settlementForm.settlements =
            this.settlementForm.settlementStart +
            "到" +
            this.settlementForm.settlementEnd;
          this.approving =
            this.approvingType[res.data.data.settlementBO.approvalStatus];
          this.approvingStatus = false;
          this.$nextTick(() => {
            this.approvingStatus = true;
          });
          this.isTrue = true;
        })
        .catch(e => {});
    },

    // 获取详情
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.settlementForm.reportUsername = res.data.data.userInfo.name;
      });
    },
    qryApproveRecord() {
      // const obj = {
      //   businessBillId: this.relationId,
      // };
      // qryApproveRecord(obj).then((res) => {
      //   res.data.data.forEach((item) => {
      //     if (item.operState === 0) {
      //       item.icon = "el-icon-time";
      //       item.color = "#F5A623";
      //     }
      //   });
      //   this.showArrpoval = true;
      //   this.activities = res.data.data;
      //   console.log(this.activities);
      // });
    },
    handleClick(tab, event) {
      console.log(tab, event, this.activeName);
      this.activeName = tab.name;
    },
    // 保存并提交操作
    submitSettlement() {
      this.settlementForm.billSource = "10";
      let params = {
        settlementBO: this.settlementForm,
        settlementBOList: this.settlementList,
        gistUploadIds: this.handleFilesParams().gistUploadIds,
        otherUploadIds: this.handleFilesParams().otherUploadIds,
        operType: 1,
        isShowPageLoading: true
      };
      editTransSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: res.data.message
        });
        this.handleBack();
      });
    },

    handleBack() {
      this.$router.back();
    },
    // 导出
    handlExport() {
      window.open(
        this.downloadUrl +
          `/apis/smp/export/exportSettleTrans?priId=${this.$route.params.id}`
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.detail-info {
  width: calc(100% - 438px);
  min-height: calc(100vh - 260px);
  float: left;
  background: #fff;
  position: relative;
  padding: 20px;
}
/deep/ .el-group-title .group-content {
  margin-top: 0;
}
.approval-read-record {
  margin-top: 0px;
}
/deep/ .ccui-app-container-detail {
  padding: 0;
  background: none;
}

.detail-info-el-Label {
  position: absolute;
  width: 107px;
  right: 33px;
  top: 31px;
  z-index: 1;
}
/deep/ .el-tabs__customize {
  padding-bottom: 50px;
}
</style>
